<template>
  <view class="login-container">
    <view class="login-content">
      <view class="login-header">
        <text class="title">手机号登录</text>
      </view>
      
      <view class="login-form">
        <view class="form-item">
          <text class="label">手机号</text>
          <view class="input-wrapper">
            <text class="area-code">+86</text>
            <input 
              class="input" 
              type="number" 
              v-model="phoneNumber" 
              placeholder="请输入手机号"
              maxlength="11"
              @input="handlePhoneInput"
            />
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">验证码</text>
          <view class="verification-wrapper">
            <input 
              class="input verification-input" 
              type="number" 
              v-model="verificationCode" 
              placeholder="请输入验证码"
              maxlength="6"
            />
            <button 
              class="code-btn" 
              :disabled="!canSendCode || isSendingCode"
              @tap="sendVerificationCode"
            >
              {{ codeButtonText }}
            </button>
          </view>
        </view>
        
        <button 
          class="login-btn" 
          :disabled="!isFormValid || isLoggingIn"
          @tap="handleLogin"
        >
          {{ isLoggingIn ? '登录中...' : '登录' }}
        </button>
      </view>
      
      <view class="login-footer">
        <text class="agreement">
          登录即表示同意
          <text class="link">《用户协议》</text>
          和
          <text class="link">《隐私政策》</text>
        </text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';
import { sendCode, login } from '../../api/login.js';
import { saveLoginInfo } from '../../utils/storage.js';

// 使用uni-app的导航API

// 响应式数据
const phoneNumber = ref('18111111111'); // 默认值，方便测试
const verificationCode = ref('');
const isSendingCode = ref(false);
const isLoggingIn = ref(false);
const countdown = ref(60);
let timer = null;

// 计算属性
const canSendCode = computed(() => {
  // 简化手机号验证：只要是11位数字即可发送验证码
  return /^1\d{10}$/.test(phoneNumber.value) && countdown.value === 60;
});

const isFormValid = computed(() => {
  // 简化表单验证：只要手机号是11位数字且验证码是6位数字即可
  return /^1\d{10}$/.test(phoneNumber.value) && 
         /^\d{6}$/.test(verificationCode.value);
});

const codeButtonText = computed(() => {
  if (isSendingCode.value) {
    return '发送中...';
  }
  if (countdown.value < 60) {
    return `${countdown.value}秒后重试`;
  }
  return '获取验证码';
});

// 处理手机号输入
const handlePhoneInput = (e) => {
  // 只保留数字
  phoneNumber.value = e.target.value.replace(/\D/g, '');
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) return;
  
  try {
    isSendingCode.value = true;
    
    // 调用发送验证码接口
    const res = await sendCode(phoneNumber.value, 'login');
    
    if (res.code === 200) {
      uni.showToast({ title: '验证码已发送', icon: 'success' });
      startCountdown();
    } else {
      uni.showToast({ title: res.msg || '发送失败', icon: 'none' });
    }
  } catch (error) {
    console.error('发送验证码失败:', error);
    uni.showToast({ 
      title: error.message || '发送失败，请稍后重试', 
      icon: 'none' 
    });
  } finally {
    isSendingCode.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

// 处理登录
const handleLogin = async () => {
  // 最简化的校验，只检查是否在登录中
  if (isLoggingIn.value) {
    return;
  }
  
  try {
    isLoggingIn.value = true;
    
    // 调用登录接口
    const res = await login(phoneNumber.value, verificationCode.value);
    
    // 只要响应成功就认为登录成功
    if (res.code === 200) {
      uni.showToast({ title: '登录成功', icon: 'success' });
      
      // 直接跳转，不需要延时
      uni.switchTab({ 
        url: '/pages/index/index',
        fail: () => {
          // 如果switchTab失败，使用navigateTo作为备选
          uni.navigateTo({ url: '/pages/index/index' });
        }
      });
    } else {
      uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
    }
  } catch (error) {
    console.error('登录失败:', error);
    uni.showToast({ 
      title: error.message || '登录失败，请稍后重试', 
      icon: 'none' 
    });
  } finally {
    isLoggingIn.value = false;
  }
};

// 清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  padding: 0 40rpx;
  box-sizing: border-box;
  background-color: #ffffff;
}

.login-content {
  width: 100%;
  max-width: 600rpx;
  margin-top: 200rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.login-header {
  text-align: center;
  margin-bottom: 80rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

.login-form {
  width: 100%;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 20rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 20rpx;
}

.area-code {
  font-size: 32rpx;
  color: #333333;
  margin-right: 20rpx;
}

.input {
  flex: 1;
  font-size: 32rpx;
  color: #333333;
  padding: 0;
  border: none;
  outline: none;
  background-color: transparent;
}

.input::placeholder {
  color: #999999;
}

.verification-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #e0e0e0;
  padding-bottom: 20rpx;
}

.verification-input {
  flex: 1;
  margin-right: 20rpx;
}

.code-btn {
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  background-color: transparent;
  color: #007aff;
  border: none;
  border-radius: 0;
  min-width: 200rpx;
}

.code-btn:disabled {
  color: #cccccc;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  font-size: 32rpx;
  color: #ffffff;
  background-color: #007aff;
  border: none;
  border-radius: 45rpx;
  margin-top: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-btn:disabled {
  background-color: #99d6ff;
}

.login-footer {
  margin-top: 80rpx;
  text-align: center;
}

.agreement {
  font-size: 24rpx;
  color: #999999;
}

.link {
  color: #007aff;
}
</style>